<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>

    const tree = {
      value: 'A',
      children: [
        {
          value: 'B',
          children: [{ value: 'D', children: [] }, { value: 'E', children: [] }]
        },
        {
          value: 'C',
          children: [{ value: 'F', children: [] }]
        }
      ]
    };

    // 深度优先遍历（DFS）
    function dfs(node) {
      if (!node) return;
      console.log(node.value);
      for (const child of node.children) {
        dfs(child);
      }
    }

    // dfs(tree); // A B D E C F


    // 广度优先遍历（BFS）
    function bfs(node) {
      const queue = [node];
      while (queue.length > 0) {
        const current = queue.shift(); // 等同于 queue.pop() 、 queue[0]、 queue.splice(0, 1)
        console.log(current.value);
        for (const child of current.children) {
          queue.push(child);
        }
      }
    }

    bfs(tree); // A B C D E F

  </script>
</body>

</html>